import 'dart:async';

import 'package:flutter_massage/common_lib/http/index.dart';
import 'package:flutter_massage/pages/model/bean.dart';
import 'package:get/get.dart';

class JsonService extends GetxService {
  static JsonService get instance => Get.find<JsonService>();

  List<TechnicianBean> _technicianList = [];
  List<ProjectBean> _projectList = [];
  List<Shop> _shopList = [];

  ///所有技师数据
  static Future<List<TechnicianBean>> getTechnicianList() async {
    if (instance._technicianList.isEmpty) {
      Completer<List<TechnicianBean>> completer = Completer();
      CommonJson.getTechnicianData((value) async {
        instance._technicianList = await CommonJson.getList(
          value,
          (json) => TechnicianBean.fromJson(json),
          keyName: '',
        );
        completer.complete(instance._technicianList);
      });
      return completer.future;
    } else {
      return instance._technicianList;
    }
  }

  ///根据id获取技师数据
  static TechnicianBean? getTechnicianById(int? id) {
    if (id == null) return null;
    return instance._technicianList.firstWhereOrNull((element) => element.id == id);
  }

  ///所有项目数据
  static Future<List<ProjectBean>> getProjectList() async {
    if (instance._projectList.isEmpty) {
      Completer<List<ProjectBean>> completer = Completer();
      CommonJson.getProjectData((value) async {
        instance._projectList = await CommonJson.getList(
          value,
          (json) => ProjectBean.fromJson(json),
          keyName: '',
        );
        completer.complete(instance._projectList);
      });
      return completer.future;
    } else {
      return instance._projectList;
    }
  }

  ///根据id获取项目数据
  static ProjectBean? getProjectById(int? itemId) {
    if (itemId == null) return null;
    return instance._projectList.firstWhereOrNull((element) => element.itemId == itemId);
  }

  ///所有店铺数据
  static Future<List<Shop>> getShopList() async {
    if (instance._shopList.isEmpty) {
      Completer<List<Shop>> completer = Completer();
      CommonJson.getShopsData((value) async {
        instance._shopList = await CommonJson.getList(
          value,
          (json) => Shop.fromJson(json),
          keyName: '',
        );
        completer.complete(instance._shopList);
      });
      return completer.future;
    } else {
      return instance._shopList;
    }
  }

  ///根据id获取店铺数据
  static Shop? getShopById(int? shopId) {
    if (shopId == null) return null;
    return instance._shopList.firstWhereOrNull((element) => element.shopId == shopId);
  }

  @override
  void onReady() {
    super.onReady();

    Future.wait([
      getTechnicianList(),
      getProjectList(),
      getShopList(),
    ]);
  }
}
